package com.smartrodin.springbootrabbitmq.config;

import com.smartrodin.springbootrabbitmq.util.Constant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: arnold_nie
 * @date: 2020/6/12 17:07
 * FileName: PushDataRabbitConfig
 * Description: 推送数据队列配置
 */
@Configuration
public class TopicRabbitConfig {

    /**
     * 交换机与队列绑定的RoutingKey
     */
    private static final String ROUTING_KEY_ORDER_PAY_STATUS = "*.orderPayStatus";
    private static final String ROUTING_KEY_ORDER_SINGLE_DISCOUNT = "*.orderSingleDiscount";

    private static final String QUEUE_DEFAULT = "queue_default";

    /**
     * 创建推送数据队列交换机
     *
     * @return the exchange
     */
    @Bean(Constant.PUSH_DATA_TOPIC_EXCHANGE)
    public Exchange pushDataExchange() {
        return ExchangeBuilder.topicExchange( Constant.PUSH_DATA_TOPIC_EXCHANGE ).durable( true ).build();
    }

    /**
     * 推送信用订单支付状态数据
     *
     * @return
     */
    @Bean(Constant.QUEUE_PUSH_ORDER_PAY_STATUS)
    public Queue queuePayStatus() {
        return new Queue( Constant.QUEUE_PUSH_ORDER_PAY_STATUS );
    }

    /**
     * 推送订单折扣
     *
     * @return
     */
    @Bean(Constant.QUEUE_PUSH_ORDER_SINGLE_DISCOUNT)
    public Queue queueSingleDiscount() {
        return new Queue( Constant.QUEUE_PUSH_ORDER_SINGLE_DISCOUNT );
    }

    /**
     * 测试
     *
     * @return
     */
    @Bean(QUEUE_DEFAULT)
    public Queue queueTest() {
        return new Queue( QUEUE_DEFAULT );
    }

    /**
     * 声明信用订单支付状态数据队列和交换机绑定关系，并且指定RoutingKey
     */
    @Bean
    public Binding orderBindingTopic(@Qualifier(Constant.QUEUE_PUSH_ORDER_PAY_STATUS) Queue queue,
                                     @Qualifier(Constant.PUSH_DATA_TOPIC_EXCHANGE) Exchange exchange) {
        return BindingBuilder.bind( queue ).to( exchange ).with( ROUTING_KEY_ORDER_PAY_STATUS ).noargs();
    }

    /**
     * 声明订单商品折扣，并且指定RoutingKey
     */
    @Bean
    public Binding orderSingleDiscountBindingTopic(@Qualifier(Constant.QUEUE_PUSH_ORDER_SINGLE_DISCOUNT) Queue queue,
                                                   @Qualifier(Constant.PUSH_DATA_TOPIC_EXCHANGE) Exchange exchange) {
        return BindingBuilder.bind( queue ).to( exchange ).with( ROUTING_KEY_ORDER_SINGLE_DISCOUNT ).noargs();
    }

    /**
     * 在一个服务中没有消费者，项目启动时不会创建交换机和队列，故在此添加一个无用队列
     *
     * @param message
     */
    @RabbitListener(queues = {QUEUE_DEFAULT})
    public void getMessage(Message message) {
        byte[] body = message.getBody();
        String msg = new String( body );
        System.out.println( "接收到默认消息:" + msg );
    }
}
